/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.live.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.LiveInterfaceType;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.live.common.model.LiveUser;
import com.yami.shop.live.common.param.LiveUsableNumParam;
import com.yami.shop.live.common.service.LiveLogService;
import com.yami.shop.live.common.service.LiveUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lhd
 * @date 2020-11-20 17:49:56
 */
@RestController
@AllArgsConstructor
@RequestMapping("/platform/live/liveUser")
@Api(tags = "平台端直播间用户接口")
public class LiveUserController {

    private final LiveUserService liveUserService;
    private final LiveLogService liveLogService;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('live:liveUser:page')")
    @ApiOperation(value = "分页查找直播间用户信息")
    public ServerResponseEntity<IPage<LiveUser>> getLiveUserPage(PageParam<LiveUser> page, LiveUser liveUser) {
        PageParam<LiveUser> liveUserPage = liveUserService.page(page, new LambdaQueryWrapper<LiveUser>()
                .like(StrUtil.isNotBlank(liveUser.getAnchorWechat()), LiveUser::getAnchorWechat, liveUser.getAnchorWechat())
                .like(StrUtil.isNotBlank(liveUser.getNickName()), LiveUser::getNickName, liveUser.getNickName())
                .like(StrUtil.isNotBlank(liveUser.getRoles()), LiveUser::getRoles, liveUser.getRoles())
                .orderByDesc(LiveUser::getUpdateTime)
        );
        for (LiveUser record : liveUserPage.getRecords()) {
            int[] roles = StrUtil.splitToInt(record.getRoles(), StrUtil.COMMA);
            StringBuilder roleStr = new StringBuilder();
            Map<Integer, String> roleMap = new HashMap<>(16);
            roleMap.put(0, I18nMessage.getMessage("yami.live.user.super.admin"));
            roleMap.put(1, I18nMessage.getMessage("yami.live.user.admin"));
            roleMap.put(2, I18nMessage.getMessage("yami.live.user.anchor"));
            roleMap.put(3, I18nMessage.getMessage("yami.live.user.operators"));
            for (int role : roles) {
                roleStr.append(roleMap.get(role));
            }
            roleStr.deleteCharAt(roleStr.length() - 1);
            record.setRoles(roleStr.toString());
        }
        return ServerResponseEntity.success(liveUserPage);
    }

    @GetMapping("/info/{liveUserId}")
    @ApiOperation(value = "通过id查询直播间商品库")
    @ApiImplicitParam(name = "liveUserId", value = "直播间用户id", required = true, dataType = "Long")
    public ServerResponseEntity<LiveUser> getById(@PathVariable("liveUserId") Long liveUserId) {
        return ServerResponseEntity.success(liveUserService.getById(liveUserId));
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('live:liveUser:save')")
    @ApiOperation(value = "新增直播间用户")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid LiveUser liveUser) throws WxErrorException {
        liveUser.setShopId(Constant.PLATFORM_SHOP_ID);
        liveUserService.saveInfo(liveUser);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('live:liveUser:update')")
    @ApiOperation(value = "修改直播间用户")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid LiveUser liveUser) {
        return ServerResponseEntity.success(liveUserService.updateById(liveUser));
    }

    @DeleteMapping("/{liveUserId}")
    @PreAuthorize("@pms.hasPermission('live:liveUser:delete')")
    @ApiOperation(value = "通过id删除直播间用户")
    @ApiImplicitParam(name = "liveUserId", value = "直播间用户id", required = true, dataType = "Long")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long liveUserId) throws WxErrorException {
        return ServerResponseEntity.success(liveUserService.removeAndWeChatById(liveUserId));
    }

    @GetMapping("/getAddProdNum")
    @ApiOperation(value = "查询商家今日剩余可用添加直播商品、可删除商品库商品次数")
    public ServerResponseEntity<LiveUsableNumParam> getAddRoomNum() {
        LiveUsableNumParam liveNum = liveLogService.getLiveNum(Constant.PLATFORM_SHOP_ID, LiveInterfaceType.ADD_LIVE_ROLE);
        LiveUsableNumParam deleteLiveNum = liveLogService.getLiveNum(Constant.PLATFORM_SHOP_ID, LiveInterfaceType.REMOVE_LIVE_ROLE);
        liveNum.setDeleteShopNum(deleteLiveNum.getShopNum());
        liveNum.setDeleteTotalNum(deleteLiveNum.getTotalNum());
        return ServerResponseEntity.success(liveNum);
    }
}
